package cn.zxl.spring.holiday.job.web.controller;

import cn.zxl.spring.holiday.job.domain.Department;
import cn.zxl.spring.holiday.job.domain.Employee;
import cn.zxl.spring.holiday.job.domain.Role;
import cn.zxl.spring.holiday.job.qo.son.EmployeeQueryObject;
import cn.zxl.spring.holiday.job.service.DepartmentService;
import cn.zxl.spring.holiday.job.service.EmployeeService;
import cn.zxl.spring.holiday.job.service.RoleService;
import cn.zxl.spring.holiday.job.util.EmployeeDataListener;
import cn.zxl.spring.holiday.job.web.json.JsonResult;
import cn.zxl.spring.holiday.job.web.log.Log;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author bofeifei
 * @since 2021-10-01
 */
@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DepartmentService departmentService;

    @RequiresPermissions(value = {"员工展示", "employee:list"}, logical = Logical.OR)
    @Log(title = "员工展示")
    @RequestMapping("/list")
    public String list(@ModelAttribute("qo") EmployeeQueryObject qo, Model model) {
        List<Department> departments = departmentService.list(null);
        model.addAttribute("departments", departments);
        PageInfo<Employee> query = employeeService.query(qo);
        model.addAttribute("pageInfo", query);
        return "employee/list";
    }

    @ResponseBody
    @RequiresPermissions(value = {"员工删除", "employee:delete"}, logical = Logical.OR)
    @Log(title = "员工删除")
    @RequestMapping("/delete")
    public JsonResult delete(Long id) {
        JsonResult jsonResult = new JsonResult();
        try {
            employeeService.deleteForEmployee(id);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMsg("请求失败");
        }
        return jsonResult;
    }

    @RequiresPermissions(value = {"员工编辑页面", "employee:input"}, logical = Logical.OR)
    @Log(title = "员工编辑页面")
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        List<Department> departments = departmentService.list(null);
        model.addAttribute("departments", departments);
        if (id != null) {
            Employee employee = employeeService.findOne(id);
            model.addAttribute("employee", employee);
            List<Role> roles = roleService.findByEmployeeId(id);
            model.addAttribute("dress", roles);
        }
        List<Role> roles = roleService.list(null);
        model.addAttribute("roles", roles);
        return "employee/input";
    }

    @ResponseBody
    @RequiresPermissions(value = {"员工编辑", "employee:saveOrUpdate"}, logical = Logical.OR)
    @Log(title = "员工编辑")
    @RequestMapping("/saveOrUpdate")
    public JsonResult saveOrUpdate(Employee employee, Long[] roleIds) {
        JsonResult jsonResult = new JsonResult();
        try {
            if (employee.getId() != null) {
                employeeService.updateEmpAndRol(employee, roleIds);
                return jsonResult;
            }
            employeeService.saveEmpAndRol(employee, roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMsg("请求失败");
        }
        return jsonResult;
    }

    @ResponseBody
    @RequestMapping("/check")
    public Map<String, Boolean> check(String username) {
        boolean excite = true;
        Employee employee = employeeService.findByUsername(username);
        if (employee != null) {
            excite = false;
        }
        Map<String, Boolean> map = new HashMap<>();
        map.put("valid", excite);
        return map;
    }

    @ResponseBody
    @RequestMapping("/download")
    public void download(HttpServletResponse response, EmployeeQueryObject qo) {
        try {
            qo.setPageSize(0);
            PageInfo<Employee> query = employeeService.query(qo);
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename*=employeeData.xlsx");
            EasyExcel.write(response.getOutputStream(), Employee.class).sheet("模板").doWrite(query.getList());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @ResponseBody
    @RequestMapping("/template")
    public void template(HttpServletResponse response) {
        try {
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename*=employeeTemplate.xlsx");
            EasyExcel.write(response.getOutputStream(), Employee.class).sheet("模板").doWrite(null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping("/importExcel")
    public JsonResult importExcel(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),
                    Employee.class,
                    new EmployeeDataListener(employeeService, departmentService)).sheet().doRead();
            return new JsonResult();
        } catch (IOException e) {
            e.printStackTrace();
            JsonResult jsonResult = new JsonResult();
            jsonResult.setSuccess(false);
            jsonResult.setMsg("上传失败");
            return jsonResult;
        }

    }
}

